//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Reader.Components;

namespace CommunityServer.Reader.Controls
{
	/// <summary>
	/// Summary description for FolderListing.
	/// </summary>
	public class AddFolder : FeedReaderTemplatedWebControl
	{

		#region Private Members

		private Button btnAddFolder;
		private TextBox txtFolderName;
		private StatusMessage lStatus;

		#endregion

		#region Constructor(s)

		public AddFolder()
		{
			
		}

		#endregion

		#region Class Methods

		protected override void AttachChildControls()
		{
			btnAddFolder	= (Button) FindControl("btnAddFolder");
			txtFolderName	= (TextBox) FindControl("txtFolderName");
			lStatus			= (StatusMessage) FindControl("lStatus");

			btnAddFolder.Click += new EventHandler(btnAddFolder_Click);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);
				DataBind();
		}


		public override void DataBind()
		{
			base.DataBind ();
			
		    Head.AddTitle("Add Folder", this.Context);
		}

		#endregion


		private void btnAddFolder_Click(object sender, EventArgs e)
		{
			string folderName = txtFolderName.Text;
			int userId = CSContext.Current.User.UserID;
			int folderId = 0;
			int parentFolderId = 0;

			
			if (Page.Request.QueryString["ID"] == null) return;


			string[] inputs = Page.Request.QueryString["ID"].Split('-');

			if (inputs.Length > 1)
			{
				if (inputs.Length > 2)
				{
					parentFolderId = Convert.ToInt32(inputs[1]);
					folderId = Convert.ToInt32(inputs[2]);
				}
			}

			if (folderName.Trim() == "")
			{
				lStatus.Text = "Please enter a valid folder name.";
				lStatus.Success = false;
				lStatus.Visible = true;
				return;
			}

			if (folderName.IndexOf('\\') >= 0 ||
				folderName.IndexOf('/') >= 0 ||
				folderName.IndexOf(':') >= 0 ||
				folderName.IndexOf('*') >= 0 ||
				folderName.IndexOf('?') >= 0 ||
				folderName.IndexOf('\"') >= 0 ||
				folderName.IndexOf('<') >= 0 ||
				folderName.IndexOf('>') >= 0 ||
				folderName.IndexOf('|') >= 0)
			{
				lStatus.Text = "Invalid characters entered. Please do not use: \\/:*?\"<>|";
				lStatus.Success = false;
				lStatus.Visible = true;
				return;
			}

		    FeedReaderDataProvider.Instance().AddFolder(userId, folderName, folderId);

			// Send response

			if (folderId == 0)
			{
			    Modal.ClosePage(this.Page, String.Format(
					returnValue, 
					Page.Request.QueryString["ID"],
					Context.Response.ApplyAppPathModifier("~/reader/FolderXml.ashx?ParentFolderId=0"),
					FeedReaderResourceManager.GetString("reader_root_node_my_feeds").Replace("'", "\\'"),
					FeedReaderResourceManager.GetString("reader_root_node_my_feeds").Replace("'", "\\'"),
					"null",
					"null"
					));
			}
			else
			{
			    ArrayList folders = FeedReaderDataProvider.Instance().GetFolders(userId, parentFolderId);
				bool folderFound = false;

				foreach (Folder f in folders)
				{
					if (f.FolderId == folderId)
					{
						folderFound = true;
					    Modal.ClosePage(this.Page, String.Format(
							returnValue, 
							Page.Request.QueryString["ID"],
							Context.Response.ApplyAppPathModifier("~/reader/FolderXml.ashx?ParentFolderId=" + f.FolderId.ToString()),
							(f.FolderName == null || f.FolderName.Trim() == "" ? "Unknown folder name" : f.FolderName + (f.UnreadCount > 0 ? " (" + f.UnreadCount + ")" : "")).Replace("'", "\\'"),
							(f.FolderName == null || f.FolderName.Trim() == "" ? "An error occurred to where no folder name was recorded for this folder. Please try to delete it and recreate it if possible." : f.FolderName + (f.UnreadCount > 0 ? " (" + f.UnreadCount + ")" : "")).Replace("'", "\\'"),
							f.UnreadCount > 0 ? "'UnreadTreeNode'" : "null",
							f.UnreadCount > 0 ? "'UnreadHoverTreeNode'" : "null"
							));

						break;
					}
				}

				if (!folderFound)
				    Modal.ClosePage(this.Page);
			}
		}

		private readonly string returnValue = "['{0}',[['ContentCallbackUrl','{1}'],['Text','{2}'],['ToolTip','{3}'],['CssClass',{4}],['HoverCssClass',{5}]]]";

	}
}
